<template>
	<view class="container">
		<view class="pusher-box">
			<live-pusher id="livePusher" ref="livePusher" class="live-pusher" :url="pushUrl" 
				mode="SD" :muted="false" :enable-camera="true" :auto-focus="true" orientation="vertical" 
				:beauty="3" whiteness="3" aspect="9:16" min-bitrate="200" max-bitrate="1000"
				@statechange="statechange" @netstatus="netstatus" 
				@error="error">
			</live-pusher>
			
			<view class="pusher-controls">
				<view class="control-item" @click="switchCamera">
					<text class="control-icon">🔄</text>
					<text class="control-text">切换</text>
				</view>
				<view class="control-item" @click="toggleBeauty">
					<text class="control-icon">💄</text>
					<text class="control-text">美颜</text>
				</view>
				<view class="control-item" @click="toggleMute">
					<text class="control-icon">{{isMuted ? '🔇' : '🔊'}}</text>
					<text class="control-text">{{isMuted ? '静音' : '声音'}}</text>
				</view>
				<view class="control-item" @click="togglePush">
					<text class="control-icon">{{isPushing ? '⏹' : '▶️'}}</text>
					<text class="control-text">{{isPushing ? '停止' : '开始'}}</text>
				</view>
			</view>
		</view>
		
		<view class="info-box">
			<view class="input-group">
				<text class="label">推流标题：</text>
				<input class="input" v-model="liveTitle" placeholder="请输入推流标题" />
			</view>
			
			<view class="input-group">
				<text class="label">推流服务器：</text>
				<input class="input" v-model="rtmpUrl" placeholder="RTMP服务器地址" />
			</view>
			
			<view class="input-group">
				<text class="label">推流流名称：</text>
				<input class="input" v-model="streamName" placeholder="推流流名称" />
			</view>
			
			<view class="status-box">
				<text class="status-title">推流状态：</text>
				<text class="status-value" :class="{'status-active': isPushing}">{{statusTips}}</text>
			</view>
		</view>
		
		<button type="primary" class="push-btn" @click="togglePush">{{isPushing ? '停止推流' : '开始推流'}}</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				context: null,
				isPushing: false,
				isMuted: false,
				isBeauty: true,
				streamName: 'stream' + Math.floor(Math.random() * 1000),
				liveTitle: '我的推流',
				statusTips: '未开始',
				netStatusZeroCount: 0
			}
		},
		computed: {
			rtmpUrl() {
				return this.$serverConfig.rtmp.liveUrl();
			},
			pushUrl() {
				return this.rtmpUrl + '/' + this.streamName;
			}
		},
		onLoad() {
			// 获取推流推流实例
			this.context = uni.createLivePusherContext('livePusher', this);
			
			// 检查RTMP服务器状态
			this.checkRtmpServer();
		},
		onReady() {
			// 开始摄像头预览
			this.context.startPreview({
				success: (res) => {
					console.log('开始预览', res);
				}
			});
		},
		onUnload() {
			// 停止推流和预览
			if (this.isPushing) {
				this.stopPush();
			}
			this.context.stopPreview();
		},
		methods: {
			// 检查RTMP服务器状态
			checkRtmpServer() {
				const serverHost = this.$serverConfig.host;
				const serverPort = this.$serverConfig.rtmp.port;
				
				console.log('正在检查RTMP服务器状态', `${serverHost}:${serverPort}`);
				
				// 使用uni.request尝试连接HTTP API（如果有）
				// 注意：这只能检查HTTP服务是否在线，不能直接检查RTMP
				uni.request({
					url: `http://${serverHost}:${serverPort}/api/stat`,
					timeout: 5000,
					success: (res) => {
						console.log('RTMP服务器HTTP API响应:', res);
					},
					fail: (err) => {
						console.warn('RTMP服务器连接检测失败，可能影响推流:', err);
						uni.showToast({
							title: 'RTMP服务器连接异常，请检查配置',
							icon: 'none',
							duration: 3000
						});
					}
				});
			},
			// 切换摄像头
			switchCamera() {
				this.context.switchCamera({
					success: (res) => {
						console.log('切换摄像头', res);
					}
				});
			},
			// 切换美颜效果
			toggleBeauty() {
				this.isBeauty = !this.isBeauty;
				if (this.isBeauty) {
					this.context.setBeauty(3);
				} else {
					this.context.setBeauty(0);
				}
			},
			// 切换静音
			toggleMute() {
				this.isMuted = !this.isMuted;
				this.context.mute({
					mute: this.isMuted
				});
			},
			// 切换推流状态
			togglePush() {
				if (this.isPushing) {
					this.stopPush();
				} else {
					this.startPush();
				}
			},
			// 开始推流
			startPush() {
				// 组合完整的推流地址
				const url = this.pushUrl;
				console.log('开始推流', url);
				console.log('推流地址详情', {
					rtmpUrl: this.rtmpUrl,
					streamName: this.streamName,
					完整地址: url
				});
				
				this.context.start({
					url: url,
					success: (res) => {
						console.log('推流成功', res);
						this.isPushing = true;
						this.statusTips = '推流中';
						
						// 推流成功，可以将推流信息提交到服务器
						this.submitLiveInfo();
					},
					fail: (err) => {
						console.error('推流失败', err);
						uni.showToast({
							title: '推流失败：' + JSON.stringify(err),
							icon: 'none'
						});
					}
				});
			},
			// 停止推流
			stopPush() {
				this.context.stop({
					success: (res) => {
						console.log('停止推流', res);
						this.isPushing = false;
						this.statusTips = '已停止';
						
						// 通知服务器推流已结束
						this.endLiveInfo();
					}
				});
			},
			// 推流状态变化事件回调
			statechange(e) {
				console.log('推流状态变化', e.detail);
				if (e.detail.code === 1007) {
					this.isPushing = true;
					this.statusTips = '推流中';
				} else if (e.detail.code === 1008) {
					this.isPushing = false;
					this.statusTips = '已停止';
				}
			},
			// 网络状态通知事件回调
			netstatus(e) {
				console.log('网络状态', e.detail);
				
				// 如果totalsize持续为0，可能存在问题
				if (e.detail.totalsize === 0 && this.isPushing) {
					this.netStatusZeroCount = (this.netStatusZeroCount || 0) + 1;
					
					// 如果连续5次totalsize为0，提示用户
					if (this.netStatusZeroCount > 5) {
						console.warn('警告：推流数据大小持续为0，可能存在推流问题');
						console.log('当前推流详情：', {
							推流地址: this.pushUrl,
							服务器: this.rtmpUrl,
							流名称: this.streamName,
							网络状态: e.detail
						});
					}
				} else {
					// 如有数据传输，重置计数器
					this.netStatusZeroCount = 0;
				}
			},
			// 错误事件回调
			error(e) {
				console.error('推流错误', e.detail);
				uni.showToast({
					title: '推流错误：' + JSON.stringify(e.detail),
					icon: 'none'
				});
			},
			// 提交推流信息到服务器（未来实现）
			submitLiveInfo() {
				// 将推流信息发送到服务器
				console.log('提交推流信息', {
					title: this.liveTitle,
					streamName: this.streamName,
					pushUrl: this.pushUrl
				});
				
				// 这里可以调用API将推流信息提交到服务器
				// uni.request({...})
			},
			// 结束推流通知（未来实现）
			endLiveInfo() {
				console.log('结束推流', this.streamName);
				// 调用API通知服务器推流已结束
			}
		}
	}
</script>

<style>
	.container {
		display: flex;
		flex-direction: column;
		min-height: 100vh;
		padding: 20rpx;
	}
	
	.pusher-box {
		width: 100%;
		position: relative;
		height: 900rpx;
		background-color: #000;
		margin-bottom: 30rpx;
	}
	
	.live-pusher {
		width: 100%;
		height: 100%;
	}
	
	.pusher-controls {
		position: absolute;
		bottom: 30rpx;
		right: 30rpx;
		display: flex;
		flex-direction: column;
	}
	
	.control-item {
		width: 80rpx;
		height: 80rpx;
		background-color: rgba(0, 0, 0, 0.5);
		border-radius: 50%;
		margin-bottom: 20rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}
	
	.control-icon {
		font-size: 36rpx;
	}
	
	.control-text {
		font-size: 20rpx;
		color: #FFFFFF;
		margin-top: 6rpx;
	}
	
	.info-box {
		background-color: #f8f8f8;
		border-radius: 12rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
	}
	
	.input-group {
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;
	}
	
	.label {
		width: 180rpx;
		font-size: 28rpx;
		color: #333;
	}
	
	.input {
		flex: 1;
		height: 70rpx;
		border: 1px solid #ddd;
		border-radius: 8rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
	}
	
	.status-box {
		display: flex;
		align-items: center;
		margin-top: 20rpx;
	}
	
	.status-title {
		font-size: 28rpx;
		color: #333;
		margin-right: 20rpx;
	}
	
	.status-value {
		font-size: 28rpx;
		color: #999;
	}
	
	.status-active {
		color: #007AFF;
	}
	
	.push-btn {
		margin-top: 30rpx;
	}
</style> 